package com.gupao.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.gupao.controller.BaseController;
import com.gupao.jwt.PassToken;
import com.gupao.jwt.UserLoginToken;
import com.gupao.model.User;
import com.gupao.service.UserService;

public class TokenInterceptor implements HandlerInterceptor {
	
	@Autowired
	UserService userService;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = request.getHeader("token");
		
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		
		if (method.isAnnotationPresent(PassToken.class)) {
			PassToken passToken = method.getAnnotation(PassToken.class);
			if (passToken.required()) {
				return true;
			}
		}
		
//		if(method.isAnnotationPresent(UserLoginToken.class)) {
//			UserLoginToken userLoginToken=method.getAnnotation(UserLoginToken.class);
//			if(userLoginToken.required()) {
				if(token==null) {
					throw new RuntimeException("无token,请重新登录！");
				}
				String uid=JWT.decode(token).getAudience().get(0);
				Integer userId=Integer.valueOf(uid);
				User user=userService.findUserById(userId);
				
				if(user==null) {
					throw new RuntimeException("用户不存在！");
				}
				
				JWTVerifier verifier=JWT.require(Algorithm.HMAC256(user.getPassword())).build();
				
				try {
					verifier.verify(token);
					Object bean=handlerMethod.getBean();
					if(bean instanceof BaseController) {
						BaseController baseController=(BaseController) bean;
						baseController.setUid(user.getId()+"");
					}
				} catch (Exception e) {
					throw new RuntimeException("401");
				}
				return true;
//			}
//		}
		
//		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
